<script setup lang="ts">
import { useCompanyStore } from "@/store/modules/company"
import { computed, onMounted, reactive, ref } from "vue"
import { Plus } from "@element-plus/icons-vue"
import { ElMessage, UploadProps, UploadRequestOptions, UploadUserFile, type FormInstance } from "element-plus"
import { type EditCompanyInfo } from "@/api/company/types/info"
import { uploadFile } from "@/api/file"
import { addressCascaderOpts } from "@/utils/transform"
import { cloneDeep } from "lodash-es"
import { basicDatumFormRules } from "./rules"

const companyStore = useCompanyStore()
const { baseCompanyInfo, getCompanyInfo, updateCompanyInfo } = companyStore

const activeTab = ref<string>("basicDatum")
const handleSwitchTab = () => {}

// 基本资料
const cascaderOpts = ref()
const basicDatumFormRef = ref<FormInstance | null>()
const basicDatumFormData = reactive<EditCompanyInfo>({
  companyShortName: null,
  companyName: null,
  companyDescription: null,
  companyPictures: [],
  companyAddress: [],
  companyEmail: null,
  companyPhone: null,
  companyLegal: null,
  companyRegisterCapital: null,
  companyRegisterDate: null
})

// @ts-expect-error
const companyPictures = computed<UploadUserFile[]>(() =>
  basicDatumFormData.companyPictures?.map((item: string) => ({
    name: item.slice().split("/").pop(),
    url: item
  }))
)
const handleUploadFile = (opts: UploadRequestOptions) => {
  const { file } = opts
  const formData = new FormData()
  formData.append("file", file)
  formData.append("biz", "company_picture")
  return uploadFile(formData)
}

const handleUploadFileSuccess: UploadProps["onSuccess"] = ({ data: url }) => {
  basicDatumFormData.companyPictures?.push(url as string)
}

const handleInformationSubmit = () => {
  const cloneFormData = {
    ...cloneDeep(basicDatumFormData),
    companyAddress: JSON.stringify(basicDatumFormData.companyAddress.map((li) => Number(li)))
  }
  basicDatumFormRef.value?.validate((valid: boolean, fields) => {
    if (valid) {
      updateCompanyInfo(cloneFormData).then((res) => {
        if (res) {
          ElMessage({
            message: "修改企业信息成功",
            type: "success"
          })
        }
      })
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}

onMounted(async () => {
  await getCompanyInfo()
  for (const attr in basicDatumFormData) {
    if (Object.prototype.hasOwnProperty.call(baseCompanyInfo, attr)) {
      // @ts-ignore
      basicDatumFormData[attr] = baseCompanyInfo[attr]
    }
  }
  cascaderOpts.value = addressCascaderOpts
})

// 修改密码
</script>

<template>
  <el-row class="company-info-container" justify="space-around" align="top">
    <el-col :span="7" class="company-info-detail">
      <el-card class="company-info-detail" shadow="always" header="企业信息">
        <el-descriptions :column="1" :label-width="300">
          <el-descriptions-item>
            <template v-if="baseCompanyInfo.companyPictures">
              <div style="display: inline-block; overflow: hidden">
                <img
                  v-for="picture of companyPictures"
                  :src="picture.url"
                  :key="picture.name"
                  width="80"
                  height="80"
                  style="object-fit: cover"
                />
              </div>
            </template>
          </el-descriptions-item>
          <el-descriptions-item label="公司简称">{{ baseCompanyInfo.companyShortName }}</el-descriptions-item>
          <el-descriptions-item label="公司全称">{{ baseCompanyInfo.companyName }}</el-descriptions-item>
          <el-descriptions-item label="公司描述">{{ baseCompanyInfo.companyDescription }}</el-descriptions-item>
          <el-descriptions-item label="公司地址">{{ baseCompanyInfo.companyAddress }}</el-descriptions-item>
          <el-descriptions-item label="公司邮箱">{{ baseCompanyInfo.companyEmail }}</el-descriptions-item>
          <el-descriptions-item label="公司电话">{{ baseCompanyInfo.companyPhone }}</el-descriptions-item>
          <el-descriptions-item label="公司法人">{{ baseCompanyInfo.companyLegal }}</el-descriptions-item>
          <el-descriptions-item label="公司注册资金">{{ baseCompanyInfo.companyRegisterCapital }}</el-descriptions-item>
          <el-descriptions-item label="公司注册时间">{{ baseCompanyInfo.companyRegisterDate }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
    </el-col>
    <el-col :span="16" class="company-info-card">
      <el-card class="company-info-card" shadow="always" header="基本资料">
        <el-tabs v-model="activeTab" @tab-click="handleSwitchTab">
          <el-tab-pane label="基本资料" name="basicDatum">
            <el-form
              ref="basicDatumFormRef"
              :model="basicDatumFormData"
              :rules="basicDatumFormRules"
              label-width="120px"
            >
              <el-form-item label="公司简称" prop="companyShortName">
                <el-input v-model.trim="basicDatumFormData.companyShortName" />
              </el-form-item>
              <el-form-item label="公司全称" prop="companyName">
                <el-input v-model.trim="basicDatumFormData.companyName" />
              </el-form-item>
              <el-form-item label="公司描述" prop="companyDescription">
                <el-input v-model.trim="basicDatumFormData.companyDescription" />
              </el-form-item>
              <el-form-item label="公司图片">
                <el-upload
                  v-model:file-list="companyPictures!"
                  action=""
                  accept=".jpg,.jpeg,.png,.gif"
                  :show-file-list="true"
                  list-type="picture-card"
                  :http-request="handleUploadFile"
                  :on-success="handleUploadFileSuccess"
                >
                  <el-icon><Plus /></el-icon>
                </el-upload>
              </el-form-item>
              <el-form-item label="公司地址" prop="companyAddress">
                <el-cascader
                  v-model="basicDatumFormData.companyAddress as any"
                  :options="cascaderOpts"
                  style="width: 400px"
                  clearable
                />
              </el-form-item>
              <el-form-item label="公司邮箱" prop="companyEmail">
                <el-input v-model.trim="basicDatumFormData.companyEmail" />
              </el-form-item>
              <el-form-item label="公司电话" prop="companyPhone">
                <el-input v-model.trim="basicDatumFormData.companyPhone" />
              </el-form-item>
              <el-form-item label="公司法人" prop="companyLegal">
                <el-input v-model.trim="basicDatumFormData.companyLegal" />
              </el-form-item>
              <el-form-item label="公司注册资金" prop="companyRegisterCapital">
                <el-input v-model.trim="basicDatumFormData.companyRegisterCapital">
                  <template #append>元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="公司注册时间" prop="companyRegisterDate">
                <el-date-picker
                  v-model="basicDatumFormData.companyRegisterDate!"
                  type="date"
                  placeholder="选择注册时间"
                />
              </el-form-item>
              <el-button type="primary" style="margin-left: 120px" @click.prevent="handleInformationSubmit"
                >提交</el-button
              >
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-col>
  </el-row>
</template>

<style scoped lang="scss">
.company-info-container {
  padding: 8px 12px;
}
</style>
